package com.example.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.utils.UserHolder;
import com.example.vd.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.utils.RedisConstants.LOGIN_USER_KEY;

@Component
public class ReFreshTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private  StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        Map<Object, Object> userDtoMap = redisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (userDtoMap.isEmpty()) {
            return true;
        }
        //把userDTO写入ThreadLocal中
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userDtoMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //6.刷新token有效期
        redisTemplate.expire(LOGIN_USER_KEY + token,30L, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
